<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑权限' : '新增权限'"
    width="900px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="权限名称" prop="name">
            <el-input
              v-model="form.name"
              placeholder="请输入权限名称"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="权限代码" prop="code">
            <el-input
              v-model="form.code"
              placeholder="请输入权限代码"
            >
              <template #append v-if="codePrefix">
                <el-button
                  @click="addPrefix"
                  type="primary"
                  size="small"
                  title="点击添加父级权限前缀"
                >
                  添加前缀: {{ codePrefix }}
                </el-button>
              </template>
            </el-input>
            <div v-if="codePrefix" style="font-size: 12px; color: #909399; margin-top: 4px;">
              💡 父级权限前缀: {{ codePrefix }}，点击右侧按钮可自动添加前缀
            </div>
            <div v-else style="font-size: 12px; color: #909399; margin-top: 4px;">
              💡 根权限，直接输入权限代码
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="权限类型" prop="type">
            <el-select
              v-model="form.type"
              placeholder="请选择权限类型"
              style="width: 100%"
            >
              <el-option label="菜单" value="menu" />
              <el-option label="按钮" value="button" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="父级权限" prop="parent_id">
            <el-tree-select
              v-model="form.parent_id"
              :data="parentOptions"
              :props="treeProps"
              placeholder="请选择父级权限"
              check-strictly
              :render-after-expand="false"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20" v-if="form.type === 'menu'">
        <el-col :span="12">
          <el-form-item label="路由路径" prop="path">
            <el-input
              v-model="form.path"
              placeholder="请输入路由路径"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="组件路径" prop="component">
            <el-input
              v-model="form.component"
              placeholder="请输入组件路径"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="图标" prop="icon">
            <el-input
              v-model="form.icon"
              placeholder="请输入图标名称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="排序" prop="sort">
            <el-input-number
              v-model="form.sort"
              :min="0"
              :max="999"
              placeholder="请输入排序"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否隐藏" prop="is_hidden">
            <el-radio-group v-model="form.is_hidden">
              <el-radio :label="0">显示</el-radio>
              <el-radio :label="1">隐藏</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="权限描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入权限描述"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          :loading="loading"
          @click="handleSubmit"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { createPermission, updatePermission, getPermissionTree } from './api'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  formData: {
    type: Object,
    default: null
  }
})

// Emits
const emit = defineEmits(['update:visible', 'success'])

// 响应式数据
const formRef = ref()
const loading = ref(false)
const parentOptions = ref([])

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const isEdit = computed(() => props.formData && props.formData.id)

// 计算父级权限前缀
const codePrefix = computed(() => {
  if (form.parent_id === 0 || !form.parent_id) {
    // 根权限，没有前缀
    return ''
  } else {
    // 子权限，需要找到父权限的代码
    const findParentCode = (options, parentId) => {
      for (const option of options) {
        if (option.id === parentId) {
          return option.code || option.name
        }
        if (option.children && option.children.length > 0) {
          const found = findParentCode(option.children, parentId)
          if (found) return found
        }
      }
      return ''
    }

    return findParentCode(parentOptions.value, form.parent_id)
  }
})

// 表单数据
const form = reactive({
  name: '',
  code: '',
  type: 'menu',
  parent_id: 0,
  path: '',
  component: '',
  icon: '',
  sort: 0,
  status: 1,
  is_hidden: 0,
  description: ''
})

// 树形组件配置
const treeProps = {
  children: 'children',
  label: 'name',
  value: 'id'
}

// 表单验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 50, message: '权限名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入权限代码', trigger: 'blur' },
    { min: 2, max: 100, message: '权限代码长度在 2 到 100 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_:]+$/, message: '权限代码只能包含字母、数字、下划线和冒号', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择权限类型', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
})

// 重置表单
const resetForm = () => {
  Object.keys(form).forEach(key => {
    if (key === 'status') {
      form[key] = 1
    } else if (key === 'sort') {
      form[key] = 0
    } else if (key === 'parent_id') {
      form[key] = 0
    } else if (key === 'is_hidden') {
      form[key] = 0
    } else if (key === 'type') {
      form[key] = 'menu'
    } else {
      form[key] = ''
    }
  })
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 获取父级权限选项
const fetchParentOptions = async () => {
  try {
    const response = await getPermissionTree()
    const permissions = response.data || []
    
    // 添加根级选项
    parentOptions.value = [
      { id: 0, name: '根级权限', children: [] },
      ...permissions
    ]
  } catch (error) {
    console.error('获取父级权限失败:', error)
    parentOptions.value = [
      { id: 0, name: '根级权限', children: [] }
    ]
  }
}

// 监听表单数据变化
watch(
  () => props.formData,
  (newData) => {
    if (newData) {
      // 编辑模式，填充表单数据
      Object.keys(form).forEach(key => {
        form[key] = newData[key] || (
          key === 'status' ? 1 :
          key === 'sort' ? 0 :
          key === 'parent_id' ? 0 :
          key === 'is_hidden' ? 0 :
          key === 'type' ? 'menu' :
          ''
        )
      })
    } else {
      // 新增模式，重置表单
      resetForm()
    }
  },
  { immediate: true }
)





// 添加父级权限前缀
const addPrefix = () => {
  if (!codePrefix.value) return

  // 如果当前代码为空，直接设置为前缀加冒号
  if (!form.code) {
    form.code = codePrefix.value + ':'
    return
  }

  // 如果当前代码已经包含前缀，不重复添加
  if (form.code.startsWith(codePrefix.value + ':')) {
    ElMessage.warning('权限代码已包含父级前缀')
    return
  }

  // 在当前代码前添加前缀
  form.code = codePrefix.value + ':' + form.code
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    loading.value = true

    const submitData = { ...form }

    // 直接使用用户输入的权限代码，不自动拼接
    // submitData.code = form.code

    if (isEdit.value) {
      await updatePermission(props.formData.id, submitData)
      ElMessage.success('更新权限成功')
    } else {
      await createPermission(submitData)
      ElMessage.success('创建权限成功')
    }

    emit('success')
  } catch (error) {
    if (error !== false) {
      ElMessage.error(isEdit.value ? '更新权限失败' : '创建权限失败')
    }
  } finally {
    loading.value = false
  }
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 初始化
onMounted(() => {
  fetchParentOptions()
})
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
